<template>
  <div
    class="certification-dialog"
    v-if="dialogVisible"
  >
    <div class="certification-box">
      <div class="certification-header">
        <div class="header-title">{{ $t('certification.name' ) }}</div>
        <div class="header-close">
          <i
            class="el-icon-close"
            @click="closeDialog"
          ></i>
        </div>
      </div>
      <div class="certification-body">
        <template v-if="!certificationState">
          <div class="certification-request-box">
            <p>{{ $t('certification.request.rule' ) }}</p>
            <p>{{ $t('certification.request.base' ) }}：</p>
            <p>1.{{ $t('certification.request.baseFirst' ) }}；</p>
            <p>2.{{ $t('certification.request.baseSecond' ) }}；</p>
          </div>
          <ul class="certification-photo-box">
            <!-- 身份证正面 -->
            <li>
              <div class="identity-card-box">
                <img
                  :src="idCardFront ? idCardFront : idCardFrontDefault"
                  alt="idcard"
                >
                <div class="upload-conatainer">
                  <input
                    type="file"
                    accept="image/*"
                    class="upload-input front-img"
                    :class="{'upload-input-circle': showUploadIdCardFrontBtn}"
                    @change="uploadFn($event, 1)"
                  >

                  <div
                    class="upload-box"
                    v-if="showUploadIdCardFrontBtn"
                  >
                    <i class="el-icon-camera-solid"></i>
                    {{ $t('certification.upload' ) }}
                  </div>

                  <div
                    class="upload-status-box"
                    v-if="isUploadFrontImg || frontImgUploadFail"
                  >
                    <el-progress
                      type="circle"
                      :width="90"
                      :stroke-width="3"
                      :color="'#67C23A'"
                      :percentage="frontImgProgress"
                      v-if="isUploadFrontImg"
                    ></el-progress>

                    <div
                      class="upload-fail-box"
                      v-if="frontImgUploadFail"
                    >
                      <p>
                        <i class="iconfont iconcircle-guanbi"></i>
                        {{ $t('certification.error.upload') }}
                      </p>
                      <el-button
                        plain
                        size="mini"
                      >
                        {{ $t('operate.reUpload') }}
                        <input
                          type="file"
                          accept="image/*"
                          class="upload-btn"
                          @change="uploadFn($event, 1)"
                        >
                      </el-button>
                    </div>
                  </div>
                </div>
              </div>
              <p class="identity-card-hint">{{ $t('certification.IDCard.front' ) }}</p>
            </li>
            <!-- 身份证背面 -->
            <li>
              <div class="identity-card-box">
                <img
                  :src="idCardBack ? idCardBack : idCardBackDefault"
                  alt="idcard"
                >
                <div class="upload-conatainer">
                  <input
                    type="file"
                    accept="image/*"
                    class="upload-input back-img"
                    :class="{'upload-input-circle': showUploadIdCardBackBtn}"
                    @change="uploadFn($event, 2)"
                  >

                  <div
                    class="upload-box"
                    v-if="showUploadIdCardBackBtn"
                  >
                    <i class="el-icon-camera-solid"></i>
                    {{ $t('certification.upload' ) }}
                  </div>

                  <div
                    class="upload-status-box"
                    v-if="isUploadBackImg || backImgUploadFail"
                  >
                    <el-progress
                      type="circle"
                      :width="90"
                      :stroke-width="3"
                      :color="'#67C23A'"
                      :percentage="backImgProgress"
                      v-if="isUploadBackImg"
                    ></el-progress>

                    <div
                      class="upload-fail-box"
                      v-if="backImgUploadFail"
                    >
                      <p>
                        <i class="iconfont iconcircle-guanbi"></i>
                        {{ $t('certification.error.upload') }}
                      </p>
                      <el-button
                        plain
                        size="mini"
                      >
                        {{ $t('operate.reUpload') }}
                        <input
                          type="file"
                          accept="image/*"
                          class="upload-btn"
                          @change="uploadFn($event, 2)"
                        >
                      </el-button>
                    </div>
                  </div>
                </div>
              </div>
              <p class="identity-card-hint">{{ $t('certification.IDCard.back' ) }}</p>
            </li>
          </ul>
        </template>

        <template v-else>
          <template v-if="certificationSuccess">
            <div class="certification-hint-box success-hint">
              <span>
                <i class="el-icon-check"></i>
              </span>
              {{ $t('certification.successHint' ) }}
            </div>
            <div class="certification-success-info">
              <div class="certification-user-img">
                <img
                  src="@/assets/images/right_idcard.png"
                  alt="idcard"
                >
              </div>
              <ul class="certification-user-info">
                <li>
                  <span class="tag-name">{{ $t('certification.info.name' ) }}：</span>
                  {{ certificationInfo.name }}
                </li>
                <li>
                  <span class="tag-name">{{ $t('certification.info.gender' ) }}：</span>
                  {{ certificationInfo.sex }}
                </li>
                <li>
                  <span class="tag-name">{{ $t('certification.info.birthday' ) }}：</span>
                  {{ certificationInfo.birth }}
                </li>
                <li>
                  <span class="tag-name">{{ $t('certification.info.IDNumber' ) }}：</span>
                  {{ certificationInfo.id_number }}
                </li>
                <li>
                  <span class="tag-name">{{ $t('certification.info.issuingAuthority' ) }}：</span>
                  {{ certificationInfo.authority }}
                </li>
                <li>
                  <span class="tag-name">{{ $t('certification.info.effectiveDate' ) }}：</span>
                  {{ certificationInfo.validDate }}
                </li>
              </ul>
            </div>
          </template>
          <template v-else>
            <div class="certification-hint-box">
              <span>
                <i class="el-icon-close"></i>
              </span>
              {{ $t('certification.failHint' ) }}
            </div>
            <div class="error-request-box">
              <p class="error-request-text">{{ $t('certification.uploadRequest' ) }}</p>
              <ul class="error-request-list">
                <li>
                  <div>
                    <img
                      src="@/assets/images/right_idcard.png"
                      alt=""
                    >
                  </div>
                  <p>
                    <i class="el-icon-check"></i>
                    {{ $t('certification.standard' ) }}
                  </p>
                </li>
                <li>
                  <div>
                    <img
                      src="@/assets/images/error_idcard_1.png"
                      alt=""
                    >
                  </div>
                  <p>
                    <i class="el-icon-close"></i>
                    {{ $t('certification.error.first' ) }}
                  </p>
                </li>
                <li>
                  <div>
                    <img
                      src="@/assets/images/error_idcard_2.png"
                      alt=""
                    >
                  </div>
                  <p>
                    <i class="el-icon-close"></i>
                    {{ $t('certification.error.second' ) }}
                  </p>
                </li>
              </ul>
            </div>
          </template>
        </template>
      </div>
      <div class="certification-footer">
        <el-button
          size="medium"
          @click="closeDialog"
        >{{ certificationSuccess ? $t('operate.close') : $t('operate.cancel') }}</el-button>
        <template v-if="!certificationSuccess">
          <el-button
            type="primary"
            size="medium"
            @click="retryFn"
            v-if="certificationState"
          >{{ $t('operate.reUpload') }}</el-button>
          <el-button
            type="primary"
            size="medium"
            @click="confirmFn"
            v-else
          >{{ $t('operate.confirm') }}</el-button>
        </template>
      </div>
    </div>
  </div>
</template>

<script>
import ObsClient from '@/assets/js/esdk-obs-browserjs-without-polyfill-3.19.5.min.js';
import { crtification } from '@/api/user';
import { errorCode } from '@/utils/index';

export default {
  name: 'Certification',
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      certificationInfo: '', //认证成功后的身份信息
      showUploadIdCardFrontBtn: true, //是否显示上传身份证正面照按钮
      showUploadIdCardBackBtn: true, //是否显示上传身份证反面照按钮
      idCardFront: '', //正面图片
      idCardBack: '', //背面图片
      idCardFrontDefault: require('@/assets/images/idcard_front.png'), //正面默认图片
      idCardBackDefault: require('@/assets/images/idcard_back.png'), //背面默认图片
      isUploadFrontImg: false, //正面照上传状态
      isUploadBackImg: false, //背面照上传状态
      frontImgProgress: 0, //正面照上传进度
      backImgProgress: 0, //背面照上传进度
      frontImgUploadFail: false, //正面照上传结果失败
      backImgUploadFail: false, //背面照上传结果失败
      certificationState: false, //是否显示认证结果页面
      certificationSuccess: false //认证是否成功
    };
  },
  methods: {
    // 创建ObsClient实例
    getObsClient() {
      let ak = 'AUAZFIGPYBDDGGEIKMLM';
      let sk = 'sckuXHMbKsebNexXTbUOramppdlxocMgFuSWkZ5S';
      let server = 'obs.cn-southwest-2.myhuaweicloud.com';
      return new ObsClient({
        access_key_id: ak,
        secret_access_key: sk,
        server: server,
        timeout: 60 * 5
      });
    },
    // 上传
    uploadFn(e, type) {
      // 还原按钮状态
      if (type === 1) {
        this.frontImgUploadFail = false;
      } else {
        this.backImgUploadFail = false;
      }

      // // 图片文件
      let file = e.target.files[0];

      if (file.type.indexOf('image') === 0) {
        let fileMaxSize = 2048; //2M
        if (file.size / 1024 > fileMaxSize) {
          let msg = this.$t('certification.error.size');
          this.hintFn('error', msg);
          // 清空input内容
          if (type === 1) {
            document.querySelector('.front-img').value = '';
          } else {
            document.querySelector('.back-img').value = '';
          }
        } else {
          // 获取上传进度百分比
          let progressBack = (transferredAmount, totalAmount) => {
            let complete = parseInt((transferredAmount * 100.0) / totalAmount);
            if (type === 1) {
              this.isUploadFrontImg = true;
              this.frontImgProgress = complete;
            } else {
              this.isUploadBackImg = true;
              this.backImgProgress = complete;
            }
          };

          let fileType = file.type.split('/')[1];
          let fileKey = `${new Date().getTime()}.${fileType}`;

          let obs = this.getObsClient();
          obs
            .putObject({
              Bucket: 'idosp2',
              Key: fileKey,
              SourceFile: file,
              ProgressCallback: progressBack
            })
            .then(res => {
              if (res.CommonMsg.Status < 300) {
                // 上传成功
                let imgPath = 'https://s1.obs.idosp.cn/' + fileKey;

                if (type === 1) {
                  // 正面
                  document.querySelector('.front-img').value = '';
                  this.showUploadIdCardFrontBtn = false;
                  this.idCardFront = imgPath;
                  this.isUploadFrontImg = false;
                  this.frontImgProgress = 0;
                } else {
                  // 背面
                  document.querySelector('.back-img').value = '';
                  this.showUploadIdCardBackBtn = false;
                  this.idCardBack = imgPath;
                  this.isUploadBackImg = false;
                  this.backImgProgress = 0;
                }
              } else {
                // 上传失败
                if (type === 1) {
                  this.showUploadIdCardFrontBtn = false;
                  this.frontImgUploadFail = true;
                  this.isUploadFrontImg = false;
                  this.frontImgProgress = 0;
                } else {
                  this.showUploadIdCardBackBtn = false;
                  this.backImgUploadFail = true;
                  this.isUploadBackImg = false;
                  this.backImgProgress = 0;
                }
              }
            });
        }
      } else {
        let msg = this.$t('certification.error.type');
        this.hintFn('error', msg);
      }
    },
    // 确认
    confirmFn() {
      if (!this.idCardFront) {
        let msg = this.$t('certification.error.front');
        this.hintFn('error', msg);
        return;
      }
      if (!this.idCardBack) {
        let msg = this.$t('certification.error.back');
        this.hintFn('error', msg);
        return;
      }

      crtification({
        id_card_top: this.idCardFront,
        id_card_bottom: this.idCardBack
      }).then(res => {
        if (res.status === 9) {
          // 认证失败
          this.hintFn('error', errorCode(res.message));
          this.certificationState = true;
          this.certificationSuccess = false;
        } else {
          // 认证成功
          this.certificationInfo = res.data;
          this.certificationState = true;
          this.certificationSuccess = true;
          this.$emit('certificationSuccess');
        }
      });
    },
    // 提示信息
    hintFn(type, message, duration = 2000) {
      this.$message({
        type,
        message,
        duration
      });
    },
    // 重新提交
    retryFn() {
      Object.assign(this.$data, this.$options.data());
    },
    // 关闭对话框
    closeDialog() {
      Object.assign(this.$data, this.$options.data());
      this.$emit('update:dialogVisible', false);
    }
  }
};
</script>

<style lang="scss" scoped>
.certification-dialog {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 2000;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.2);

  .certification-box {
    width: 720px;
    background-color: #fff;

    .certification-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 100%;
      height: 48px;
      padding: 0 15px;
      font-size: 18px;

      .header-title {
        color: #303133;
      }

      .header-close {
        color: #909399;
      }
    }

    .certification-body {
      width: 100%;
      padding: 30px 20px;

      .certification-request-box {
        width: 100%;
        padding: 15px;
        padding-top: 5px;
        background-color: #fbfdff;

        p {
          margin-top: 10px;

          &:nth-of-type(1) {
            color: #754545;
          }

          &:nth-of-type(2) {
            color: #303133;
          }
        }
      }

      .certification-photo-box {
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 100%;
        margin-top: 20px;

        li {
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          align-items: center;
          width: 320px;
          height: 230px;

          .identity-card-box {
            position: relative;
            width: 100%;
            height: 200px;
            overflow: hidden;

            img {
              width: 100%;
              object-fit: cover;
            }

            .upload-conatainer {
              position: absolute;
              top: 0;
              left: 0;
              width: 100%;
              height: 100%;
            }

            .upload-box {
              position: absolute;
              top: 50%;
              left: 50%;
              transform: translate(-50%, -50%);
              display: flex;
              flex-direction: column;
              justify-content: center;
              align-items: center;
              width: 96px;
              height: 96px;
              border-radius: 50%;
              color: var(--color-primary);
              font-size: 13px;
              background-color: #ebf1ff;

              i {
                margin-bottom: 4px;
                font-size: 30px;
              }
            }

            .upload-input {
              position: absolute;
              top: 0;
              left: 0;
              width: 100%;
              height: 100%;
              opacity: 0;
            }

            .upload-input-circle {
              top: 50%;
              left: 50%;
              z-index: 1;
              transform: translate(-50%, -50%);
              width: 96px;
              height: 96px;
              border-radius: 50%;
            }

            .upload-status-box {
              position: absolute;
              top: 0;
              left: 0;
              z-index: 1;
              display: flex;
              justify-content: center;
              align-items: center;
              width: 100%;
              height: 100%;
              background: rgba(0, 0, 0, 0.75);

              ::v-deep .el-progress__text {
                color: #fff;
                font-size: 18px !important;
              }

              .upload-fail-box {
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;

                p {
                  display: flex;
                  align-items: center;
                  margin-bottom: 24px;
                  color: #f56c6c;

                  i {
                    margin-right: 6px;
                  }
                }

                .el-button {
                  position: relative;
                  width: 90px;
                  color: #fff;
                  font-size: 12px;
                  background-color: transparent;

                  &:hover {
                    color: var(--color-primary);
                  }

                  .upload-btn {
                    position: absolute;
                    top: 0;
                    left: 0;
                    width: 100%;
                    height: 100%;
                    opacity: 0;
                  }
                }
              }
            }
          }

          .identity-card-hint {
            color: #909399;
          }
        }
      }

      .certification-hint-box {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        height: 36px;
        padding: 0 20px;
        font-size: 20px;

        span {
          flex-shrink: 0;
          display: flex;
          justify-content: center;
          align-items: center;
          width: 36px;
          height: 36px;
          margin-right: 15px;
          border-radius: 50%;
          background-color: #fef0f0;
          color: #f56c6c;
        }
      }

      .error-request-box {
        width: 100%;
        margin-top: 20px;
        padding: 20px;
        background-color: #fbfdff;

        .error-request-text {
          font-size: 16px;
        }

        .error-request-list {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-top: 15px;

          li {
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            align-items: center;
            width: 192px;
            height: 148px;

            div {
              width: 100%;
              height: 120px;
              background-color: #f2f2f2;
            }

            p {
              i {
                &.el-icon-check {
                  color: #67c23a;
                }
                &.el-icon-close {
                  color: #f56c6c;
                }
              }
            }
          }
        }
      }

      .success-hint {
        span {
          background-color: #f0f9eb;
          color: #67c23a;
        }
      }

      .certification-success-info {
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 100%;
        gap: 30px;
        margin-top: 30px;

        .certification-user-img {
          width: 320px;
          height: 200px;
          border-radius: 10px;
          background-color: #f2f2f2;
          overflow: hidden;

          img {
            width: 100%;
            object-fit: cover;
          }
        }

        .certification-user-info {
          flex: 1;

          li {
            display: flex;
            align-items: center;
            margin-bottom: 15px;

            .tag-name {
              color: #909399;
            }
          }
        }
      }
    }

    .certification-footer {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      width: 100%;
      height: 66px;

      .el-button {
        margin-left: 0;
        margin-right: 15px;
      }
    }
  }
}
</style>
